package com.yuwei.movie

import android.view.View
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.yuwei.base.RoutePath
import com.yuwei.database.entity.MovieEntity
import com.yuwei.database.entity.MovieEntityItem
import com.yuwei.common.mvi.BaseMviFragment
import com.yuwei.common.mvi.UiState
import com.yuwei.database.entity.VideoParamEntity
import com.yuwei.movie.adapter.MovieListAdapter
import com.yuwei.movie.adapter.MovieTypeAdapter
import com.yuwei.movie.databinding.FragmentMovieBinding
import com.yuwei.movie.demo.MovieIntent
import com.yuwei.movie.demo.MovieViewModel
import com.yuwei.movie.entity.*
import java.text.SimpleDateFormat
import kotlinx.coroutines.launch

@Route(path = RoutePath.MOVIE_FRAGMENT)
class MovieFragment : BaseMviFragment<FragmentMovieBinding, MovieViewModel>() {
    private val movieTypeAdapter = MovieTypeAdapter()
    private lateinit var  movieListAdapter:MovieListAdapter
    private var pageIndex = 1
    private var pageSize = 10
    private var mPosition = 0
    private var Position = 0

    private var simpleVideoList = mutableListOf<MovieEntityItem>()
    private val mTabList = mutableListOf<MovieTypeEntityItem>()

    override fun successData(it: UiState.onSuccess<*>) {
        when (it.type) {
            "getMovieType" -> {
                val data = it.data as MovieTypeEntity
                //添加分类Tab
                mTabList.add(MovieTypeEntityItem("", 0, -1, 0, "", "推荐"))
                mTabList.addAll(data)
                movieTypeAdapter.data.addAll(mTabList)
                movieTypeAdapter.notifyDataSetChanged()
            }
            "getMovieRecommend" -> {
                val data = it.data as MovieEntity
                if (pageIndex == 1){
                    binding.movieSmart.finishRefresh()
                    simpleVideoList.clear()
                }

                simpleVideoList.addAll(data)
                movieListAdapter.addItems(simpleVideoList)
                movieListAdapter.notifyDataSetChanged()
            }

            "insertVideo"->{
                ToastUtils.showShort("添加成功")
            }

        }
    }

    override fun failureData(error: String) {
        LogUtils.d(error)
    }

    override fun initView() {
        //添加下拉刷新监听
        binding.movieSmart.setOnRefreshListener {
            pageIndex = 1
            refreshOrMoreList()
        }

        movieListAdapter = MovieListAdapter(simpleVideoList).apply {
            preloadEndCount = 4
            preloadMoreData = {
                pageIndex += 1
                refreshOrMoreList()
            }
        }
        //漏斗
        Glide.with(this).load(R.drawable.hopper).into(binding.movieHopperIv)
        //type
       binding.movieType.adapter = movieTypeAdapter
        binding.movieType.layoutManager = LinearLayoutManager(requireContext(),LinearLayoutManager.HORIZONTAL,false)
        vm.sendIntent(MovieIntent.getMovieList)
        //type点击交互
        movieTypeAdapter.setOnItemClickListener { adapter, view, position ->
            mTabList.clear()
            mPosition = position
            movieTypeAdapter.setPosition(mPosition)
            movieTypeAdapter.notifyDataSetChanged()
            Position = 19+mPosition
            movieListAdapter.getClos()
            refreshOrMoreList()
        }
        binding.movieRv.run {
            setItemViewCacheSize(12) //设置屏幕外ViewHolder缓存数量，默认为2
            setHasFixedSize(true) //减少固定大小的子组件反复测量
            setRecycledViewPool(RecyclerView.RecycledViewPool().apply {
                setMaxRecycledViews(0, 10) //根据不同的组件类型缓存
            })
            setViewCacheExtension(MovieItemCache(binding.movieRv)) //自定义缓存

            //滚动时停止图片加载
            addOnScrollListener(object : RecyclerView.OnScrollListener(){
                override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                    if (newState == RecyclerView.SCROLL_STATE_IDLE){
                        Glide.with(this@MovieFragment).resumeRequests()
                    }else{
                        Glide.with(this@MovieFragment).pauseRequests()
                    }
                }
            })

            //关闭不必要动画
            (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false

            //设置布局管理器和数据适配器
            binding.movieRv.layoutManager = GridLayoutManager(requireContext(),2)
            binding.movieRv.adapter = movieListAdapter
            vm.sendIntent(MovieIntent.getVideoRecommend(pageIndex, pageSize))
        }


        //点击事件
        movieListAdapter.setItemOnClickListener(object : MovieListAdapter.OnItemClickListener{
            override fun onItemClick(v: View, position: Int) {
                when(v.id){
                    R.id.movie_list_iv ->{
                        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                        vm.sendIntent(MovieIntent.insertVideo(VideoParamEntity(
                            videoDesc = simpleVideoList[position].description,
                            playUrl = simpleVideoList[position].videopath,
                            title = simpleVideoList[position].name,
                            authorIcon = simpleVideoList[position].avatar_url,
                            videoMainImage = simpleVideoList[position].videomainimag,
                            authorName = simpleVideoList[position].name,
                            videoType = "视频",
                            createTime = sdf.format(System.currentTimeMillis())
                        )))
                        ARouter.getInstance().build(RoutePath.VIDEO_PLAY_DETAIL).withSerializable("movie", movieListAdapter.getData(position)).navigation()
                    }

                }
            }
        })

    }

    override fun initData() {

    }
    private fun refreshOrMoreList(){
        lifecycleScope.launch {
            if (mPosition == 0){
                vm.sendIntent(MovieIntent.getVideoRecommend(pageIndex, pageSize))
            }else{
                vm.sendIntent(MovieIntent.getVideoList(pageIndex, pageSize,Position))
            }
        }
    }
}